<template>
  <div class="map-wrap">
    <div class="return-btn" v-show="showReturn">
      <el-button type="primary" @click="returnUpLevel">返回上一级</el-button>
    </div>
    <Echart ref="mapRef" :height="950" :options="areaChartOptions" />
  </div>
</template>

<script setup lang="ts">
import china from '@/assets/map/json/china_1.json'
import echarts from '@/plugins/echarts'
import { Echart } from '@/components/Echart'
import type { EChartsOption } from 'echarts'
import { getAreaStatistics } from '@/api/areaView'

const mapJson = import.meta.glob('@/assets/map/json/province/*.json')

const emits = defineEmits(['return', 'goDown', 'citySelect'])

echarts?.registerMap('china', china as any)

let mapInstance: Nullable<echarts.ECharts> | undefined

const mapRef = ref<InstanceType<typeof Echart>>()
const showReturn = ref(false)

const areaChartOptions = reactive<EChartsOption>({
  tooltip: {
    trigger: 'item',
    show: true,
    formatter: function (params) {
      let num1 = 0
      let num2 = 0
      if (params.data && params.data.value) {
        num1 = params.data.value[0]
        num2 = params.data.value[1]
      }
      return `数据库资产：${num1}<br/>文件资产：${num2}`
    }
  },
  series: [
    {
      type: 'map',
      map: 'china',
      label: {
        show: true
      },
      roam: true,
      selectedMode: 'single',
      data: []
    }
  ]
}) as EChartsOption

//用来存放下钻的历史记录
let history = [
  {
    name: 'china',
    code: ''
  }
]

let currentName = ''

async function goDown({ code, name }) {
  if (!mapInstance) return
  //获取地图数据之后，修改地图options
  if (!echarts.getMap(code)) {
    const newMapJson = await getMapJson(code)
    echarts.registerMap(name, newMapJson)
  }
  getData(code)
  showReturn.value = true
  areaChartOptions.series![0].map = name
  history.push({
    name,
    code
  })
}

function returnUpLevel() {
  if (history.length <= 1) {
    return false
  }

  history.pop() //弹出最后一个

  const mapName = history[history.length - 1].name
  //修改地图配置重新绘制地图
  showReturn.value = false
  areaChartOptions.series![0].map = mapName
  emits('return')
  getData()
}

async function getMapJson(name) {
  const res = Object.entries(mapJson).find(([path]) => {
    return path.includes(name)
  })
  if (res) {
    const [, mod] = res
    const jsonData = (await mod()) as any
    return jsonData.default
  }
}

onMounted(() => {
  getData()

  mapInstance = mapRef.value?.getChartInstance()

  if (!!mapInstance) {
    mapInstance.on('click', function (params: any) {
      if (params.componentSubType === 'map' && params.data) {
        const areaCode = params.data.value[2]
        if (history.length > 1) {
          emits('citySelect', {
            code: areaCode,
            name: params.name,
            unSelect: currentName === params.name //是否取消选择
          })

          currentName = currentName === params.name ? '' : params.name
        } else {
          goDown({ code: areaCode, name: params.name })
          currentName = ''
          emits('goDown', { code: areaCode, name: params.name })
        }
      }
    })
  }
})

async function getData(provinceId?: number) {
  const { data } = await getAreaStatistics({
    page: 1,
    pageSize: 100,
    provinceId
  })
  areaChartOptions.series![0].data = data.map((item) => {
    return {
      name: item.areaName,
      value: [item.dbCount, item.fileCount, item.areaId]
    }
  })
}

function setMapActive(name: string) {
  mapInstance?.dispatchAction({
    type: 'select',
    name
  })
  currentName = currentName === name ? '' : name
}

defineExpose({
  goDown,
  getMapInstance: () => mapInstance,
  getHistory: () => history,
  setMapActive
})
</script>

<style lang="scss" scoped>
.map-wrap {
  position: relative;
  .return-btn {
    position: absolute;
    left: 0;
    top: 0;
    cursor: pointer;
    z-index: 99;
  }
}
</style>
